<?php

namespace App\Store\Models\Goods\GoodsSend;

use App\Common\Services\Common;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Account\SiteStore;

class GoodsSendgoods extends Model
{
    protected $table = 'site_goods_sendgoods';
    public $timestamps = false;
    protected $primaryKey = 'id';
    protected $guarded = ['_token'];

    public static function getList(Request $request){
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $query = self::with(['storeinfo'])->where(['cp_id' => $cp_id, 'is_del' => 1])->orderBy('create_at', 'desc');
        $store_ids = StoreCommon::getCurrentAccountStoreId($request);

        if($store_ids){//权限控制
            if(is_array($store_ids)){//获取当前权限下的门店
                $query->whereIn('store_id',$store_ids);
            }
            if(is_numeric($store_ids) && intval($store_ids)>0){//获取当前门店下的列表
                $query->where('store_id', intval($store_ids));
            }
        }
        $ids=$request->ids;
        $ids=is_array($ids)?$ids:(is_array(json_decode($ids,true))?json_decode($ids,true):[]);
        if(count($ids)>0){
            $query->whereIn('id',$ids);
        }

        $store_id = $request->store_id;//下拉单选搜索
        if ($store_id>0) {
            $query->where('store_id', $store_id);
        }

        $sendgoods_name = $request->sendgoods_name;
        if ($sendgoods_name!='') {
            $query->where('sendgoods_name', 'like','%'.$sendgoods_name.'%');
        }

        $goods_sn_code = $request->goods_sn_code;
        if ($goods_sn_code!='') {
            $query->where('goods_sn_code', 'like','%'.$goods_sn_code.'%');
        }

        
        $start_time = (!is_numeric($request->start_time) && strtotime($request->start_time) > 0) ? strtotime($request->start_time) : intval($request->start_time);
        $end_time = (!is_numeric($request->end_time) && strtotime($request->end_time) > 0) ? strtotime($request->end_time) : intval($request->end_time);
        if ($start_time > 0 && $end_time > $start_time) {
            $query->where('create_at', '>=', $start_time)->where('create_at', '<=', $end_time);
        }
        


        $isgetall = intval($request->isgetall) ?? 0;


        if ($isgetall == 0) {
            $limit = $request->limit ?? 10;
            $list = $query->paginate($limit)->toArray();
            return Common::paginateDataToArray($list);
        } else {
            $list = $query->get()->toArray();
            return ['list' => $list];
        }
    }

    public function storeinfo(){
        return $this->hasOne(SiteStore::class, 'id', 'store_id')->select(['id', 'store_name']);
    }
}